package com.asd.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.asd.common.Result;
import com.asd.common.constant.CommonConstant;
import com.asd.system.entity.LoginModel;
import com.asd.system.entity.User;
import com.asd.system.service.IUserService;
import com.asd.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Api(tags = "登录接口Api")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";


    /**
     * 登录入口
     *
     * @param loginModel
     * @return
     */
    @ApiOperation("带验证码登录入口")
    @PostMapping(value = "/login1")
    public Result<?> login1(@RequestBody LoginModel loginModel) {
        Result<JSONObject> result = new Result<JSONObject>();

        String username = loginModel.getUsername();
        String password = loginModel.getPassword();

        //  校验验证码
        String captcha = loginModel.getCaptcha();
        if (captcha == null) {
            result.error500("验证码无效");
            return result;
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha + loginModel.getCheckKey(), "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if (checkCode == null || !checkCode.equals(lowerCaseCaptcha)) {
            result.error500("验证码错误");
            return result;
        }

        //update-end-author:taoyan date:20190828 for:校验验证码

        //1. 校验用户是否有效
        User user = userService.findToName(username);
        result = userService.checkUserIsEffective(user);
        if (!result.isSuccess()) {
            redisUtil.set("sucess_login", false, 1000 * 60);
            return result;
        }

        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, user.getSalt());
        String syspassword = user.getPassWord();
        if (!syspassword.equals(userpassword)) {
            redisUtil.set("sucess_login", false, 1000 * 60);
            result.error500("用户名或密码错误");
            return result;
        }

        //校验用户状态
        if (user.getIsEnable().equals("0")){
            redisUtil.set("sucess_login", false, 1000 * 60);
            result.error500("账号未激活，请联系管理员添加账号！");
            return result;
        }



        //用户登录信息
        userInfo(user, result);
        redisUtil.del("sucess_login");

        return result;

    }


    /**
     * 登录入口
     *
     * @param loginModel
     * @return
     */
    @ApiOperation("登录入口")
    @PostMapping(value = "/login")
    public Result<?> login(@RequestBody LoginModel loginModel) {
        Result<JSONObject> result = new Result<JSONObject>();

        String username = loginModel.getUsername();
        String password = loginModel.getPassword();

        //1. 校验用户是否有效
        User user = userService.findToName(username);
        result = userService.checkUserIsEffective(user);
        if (!result.isSuccess()) {
            redisUtil.set("sucess_login", false, 1000 * 60);
            return result;
        }

        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, user.getSalt());
        String syspassword = user.getPassWord();
        if (!syspassword.equals(userpassword)) {
            redisUtil.set("sucess_login", false, 1000 * 60);
            result.error500("用户名或密码错误");
            return result;
        }

        //用户登录信息
        userInfo(user, result);
        redisUtil.del("sucess_login");

        return result;

    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public Result<?> logout(HttpSession session) {
        session.invalidate();
        return Result.ok("安全退出");
    }


//    /**
//     * 退出登录
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/logout")
//    public Result<Object> logout(HttpServletRequest request) {
//        //用户退出逻辑
//        String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
//        if(oConvertUtils.isEmpty(token)) {
//            return Result.error("退出登录失败！");
//        }
//        String username = JwtUtil.getUsername(token);
//        User user = userService.findToName(username);
//        if(user!=null) {
//            //清空用户登录Token缓存
//            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
//            //清空用户登录Shiro权限缓存
//            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + user.getId());
//            //清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
//            redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, user.getUserName()));
//            //调用shiro的logout
//            SecurityUtils.getSubject().logout();
//            return Result.ok("退出登录成功！");
//        }else {
//            return Result.error("Token无效!");
//        }
//    }


    /**
     * 后台生成图形验证码 ：有效
     *
     * @param
     * @param key
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage")
    public Result<String> randomImage(@RequestParam("key") String key) {
        Result<String> res = new Result<String>();
        try {
            String code = RandomUtil.randomString(BASE_CHECK_CODES, 4);
            String lowerCaseCode = code.toLowerCase();
            String realKey = MD5Util.MD5Encode(lowerCaseCode + key, "utf-8");
            redisUtil.set(realKey, lowerCaseCode, 60);
            String base64 = RandImageUtil.generate(code);
            res.setSuccess(true);
            res.setResult(base64);
        } catch (Exception e) {
            res.error500("获取验证码出错" + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 图形验证码
     *
     * @param sysLoginModel
     * @return
     */
    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    public Result<?> checkCaptcha(@RequestBody LoginModel sysLoginModel) {
        String captcha = sysLoginModel.getCaptcha();
        String checkKey = sysLoginModel.getCheckKey();
        if (captcha == null) {
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha + checkKey, "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if (checkCode == null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }
        return Result.ok();
    }


    /**
     * 用户信息
     *
     * @param user
     * @param result
     * @return
     */
    private Result<JSONObject> userInfo(User user, Result<JSONObject> result) {
        String password = user.getPassWord();
        String username = user.getUserName();
        // 生成token
        String token = JwtUtil.sign(username, password);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);

        // 获取用户部门信息
        JSONObject obj = new JSONObject();

        //获取用户角色信息

//        List<SysDepart> departs = sysDepartService.queryUserDeparts(user.getId());
//        obj.put("departs", departs);
//        if (departs == null || departs.size() == 0) {
//            obj.put("multi_depart", 0);
//        } else if (departs.size() == 1) {
//            sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
//            obj.put("multi_depart", 1);
//        } else {
//            obj.put("multi_depart", 2);
//        }
        obj.put("token", token);
        obj.put("userInfo", user);
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }
}

